package com.clhbolg.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clhbolg.domain.Article;
import com.clhbolg.domain.Category;
import com.clhbolg.domain.bo.CategoryBo;
import com.clhbolg.domain.vo.CategoryVo;
import com.clhbolg.mapper.ArticleMapper;
import com.clhbolg.mapper.CategoryMapper;
import com.clhbolg.model.dto.CategoryAdminDTO;
import com.clhbolg.model.dto.CategoryDTO;
import com.clhbolg.model.vo.request.CategoryVO;
import com.clhbolg.model.vo.request.ConditionVO;
import com.clhbolg.service.ICategoryService;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 分类Service业务层处理
 *
 * @author cailinhu
 * @date 2023-02-08
 */
@RequiredArgsConstructor
@Service
@DS("slave")
public class CategoryServiceImpl implements ICategoryService {

    private final CategoryMapper baseMapper;

    @Resource
    private ArticleMapper articleMapper;

    /**
     * 查询分类
     */
    @Override
    public CategoryVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询分类列表
     */
    @Override
    public TableDataInfo<CategoryVo> queryPageList(CategoryBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<Category> lqw = buildQueryWrapper(bo);
        Page<CategoryVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询分类列表
     */
    @Override
    public List<CategoryVo> queryList(CategoryBo bo) {
        LambdaQueryWrapper<Category> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Category> buildQueryWrapper(CategoryBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Category> lqw = Wrappers.lambdaQuery();
//        lqw.select(Category::getCategoryName,Category::getId, BaseEntity::getCreateTime,BaseEntity::getUpdateTime)
        lqw.like(StringUtils.isNotBlank(bo.getCategoryName()), Category::getCategoryName, bo.getCategoryName());
        return lqw;
    }

    /**
     * 新增分类
     */
    @Override
    public Boolean insertByBo(CategoryBo bo) {
        Category add = BeanUtil.toBean(bo, Category.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改分类
     */
    @Override
    public Boolean updateByBo(CategoryBo bo) {
        Category update = BeanUtil.toBean(bo, Category.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Category entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除分类
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
            Long count = articleMapper.selectCount(Wrappers.lambdaQuery(Article.class).in(Article::getCategoryId, ids));
            if (count>0)
                throw new GlobalException("被删除的分类已经被引用");

        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public List<CategoryVo> queryList(String keywords) {
        CategoryBo categoryBo = new CategoryBo();
        categoryBo.setCategoryName(keywords);
        return queryList(categoryBo);
    }

    @Override
    public TableDataInfo<CategoryAdminDTO> listCategoriesAdmin(ConditionVO vo, PageQuery pageQuery) {
        //开始连表查询吧
        Page<CategoryAdminDTO> categoriesAdmin= baseMapper.listCategoriesAdmin(vo,pageQuery.build());
        return TableDataInfo.build(categoriesAdmin);
    }

    @Override
    public void saveOrUpdate(CategoryVO categoryVO) {
        CategoryVo vo = baseMapper.selectVoOne(Wrappers.lambdaQuery(Category.class).eq(Category::getCategoryName, categoryVO.getCategoryName()));
        if (vo!=null&&vo.getCategoryName().equals(categoryVO.getCategoryName())){
            throw  new GlobalException("分类名称已经存在") ;
        }
        Category convert = Convert.convert(Category.class, categoryVO);
        baseMapper.insertOrUpdate(convert);
    }

    @Override
    public List<CategoryDTO> listCategories() {
        //查出跟文章相关的分类
        List<CategoryDTO> s =  baseMapper.listCategories();
        return s;
    }
}
